import * as os from 'os';
import * as path from 'path';
import * as fse from 'fs-extra';
import { copyCoverImage, parseContentOpf, parseRootFile, unzip, copyUnzipBook } from 'src/utils/parse-book';
import { BOOK_PATH } from '../../utils/const'

const TEMP_PATH = 'tmp-book'

class BookEpubParse {
  constructor(bookPath, file) {
    this.bookPath = bookPath;
    this.file = file;
  }

  private bookPath: string;
  private file: any;
  async parse() {
    console.log('电子书解析', this.bookPath, this.file);
    // 1. 生成临时文件
    const fileName = decodeURIComponent(this.file.originalname)
    // const homeDir = os.homedir();
    // const tmpDir = path.resolve(homeDir, TEMP_PATH);
    const tmpDir = path.resolve(BOOK_PATH, TEMP_PATH).replace(/\\/g, '/');
    const tmpFile = path.resolve(tmpDir, fileName);
    // console.log("🚀 ~ BookEpubParse ~ parse ~ homeDir:", homeDir, tmpDir, tmpFile)
    fse.copySync(this.bookPath, tmpFile);
    // 2. 生成 epub 电子书解析文件夹路径
    const tmpUnzipDirName = fileName.replace('.epub', '');
    const tmpUnzipDir = path.resolve(tmpDir, tmpUnzipDirName);
    // console.log("🚀 ~ BookEpubParse ~ parse ~ tmpUnzipDir:", tmpUnzipDir)
    fse.mkdirpSync(tmpUnzipDir);
    // 3. 解压 epub 电子书
    unzip(this.bookPath, tmpUnzipDir)
    // 4. 解析 epub 电子书, 获取 rootfile 根文件地址
    const opfPath = await parseRootFile(tmpUnzipDir)
    // console.log("🚀 ~ BookEpubParse ~ parse ~ opfPath:", opfPath)
    // 5. 解析 epub 电子书, 获取 content opf 电子书信息和目录
    const bookData = await parseContentOpf(tmpUnzipDir, opfPath, fileName)
    // console.log("🚀 ~ BookEpubParse ~ parse ~ bookData:", bookData)
    // 6. 复制封面图片
    const cover = copyCoverImage(bookData, tmpDir)
    // console.log("🚀 ~ BookEpubParse ~ parse ~ cover:", cover)
    bookData.cover = cover
    // 7. 复制电子书内容
    copyUnzipBook(tmpUnzipDir, tmpUnzipDirName)
    // 8. 删除临时文件
    fse.removeSync(tmpFile);
    fse.removeSync(tmpUnzipDir);

    return bookData;
  }

}

export default BookEpubParse;
